function y = trim_by_env(x, tol)
% function y = trim_by_env(x, tol)
%
% Removes regions of a vector/waveform with sufficiently low values using
% the waveform's envelope.  WARNING: this function assumes that the
% undesirable region is at the END of the vector and therefore removes
% everything from the first found low region to the end. 
% 
% Input:
%   x   [vec] - The signal to trim
%   tol [num] - The threshold value for removal (anything below this value
%               and until the end of the vector gets removed)
%               [0.025*max(abs(x))]
%
% Output:
%   y   [vec] - The trimmed vector
%

% Copyright (C) 2010-2030 Graham Grindlay (grindlay@ee.columbia.edu)
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.

if nargin < 2 || isempty(tol)
    tol = 0.025*max(abs(x));
end

env = calc_env(x);
ndx = find(env>tol);
y = x(1:ndx(end));
